package juc;

import com.alibaba.druid.sql.dialect.oracle.ast.stmt.OracleMultiInsertStatement;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class ShareResource{
    private int flag=1;



    private Lock lock=new ReentrantLock();

    private Condition condition1=lock.newCondition();
    private Condition condition2=lock.newCondition();
    private Condition condition3=lock.newCondition();

    public void consumerA(int l){
        lock.lock();
        try {
            while (flag!=1){
                condition1.await();
            }
            for (int i=0;i<5;i++){
                System.out.println(Thread.currentThread().getName()+"正在第"+(i+1)+"打印！！！轮次:"+l);
            }
            flag=2;
            condition2.signalAll();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }
    public void consumerB(int l){
        lock.lock();
        try {
            while (flag!=2){
                condition2.await();
            }
            for (int i=0;i<10;i++){
                System.out.println(Thread.currentThread().getName()+"正在第"+(i+1)+"打印！！！轮次:"+l);
            }
            flag=3;
            condition3.signalAll();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }
    public void consumerC(int l){
        lock.lock();
        try {
            while (flag!=3){
                condition3.await();
            }
            for (int i=0;i<15;i++){
                System.out.println(Thread.currentThread().getName()+"正在第"+(i+1)+"打印！！！轮次:"+l);
            }
            flag=1;
            condition1.signalAll();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }
}

public class p13 {
    public static void main(String[] args) {
        ShareResource share=new ShareResource();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i=1;i<=10;i++){
                    share.consumerA(i);

                }
            }
        },"A").start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i=1;i<=10;i++){
                    share.consumerB(i);
                }
            }
        },"B").start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i=1;i<=10;i++){
                    share.consumerC(i);
                }
            }
        },"C").start();

    }
}
